<template>
  <!-- 工时维护店端-经销商端页面 -->
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="4" :labelWidth="90" :formType="type" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <button-area :style="{ paddingLeft: '80px' }"></button-area>
    <BreakSpace label="维修项目" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <!-- 添加维修项目 -->
    <FilterTable
      ref="table1gjp"
      :columns="columns1"
      selectionType="single"
      :height="'200px'"
      :datakey="'rows'"
      :params="fetchParams"
      :dataSource="datasourceTablefirst"
      :onColumnsChange="columns => (this.columns1 = columns)"
      :onSyncTableData="addWXXM"
      :isSelectColumn="false"
      :isPagination="false"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" :disabled="AddProject" @click="openAddWxxm">新增</el-button>
      </template>
    </FilterTable>
    <template>
      <BreakSpace label="配件" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    </template>
    <!-- 添加配件 -->
    <FilterTable
      ref="table2"
      :columns="columns2"
      :height="'200px'"
      :datakey="'rows'"
      :dataSource="datasourceTablesecond"
      :params="fetchParams1"
      :onColumnsChange="columns => (this.columns2 = columns)"
      :isSelectColumn="false"
      :isPagination="false"
    >
      <template slot="controls">
        <el-button size="small" type="primary" :disabled="AddProject1" icon="el-icon-plus" @click="openReCom">新增</el-button>
      </template>
    </FilterTable>
    <BreakSpace v-if="this.type === 'show'" label="变更履历" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <!-- 添加配件 -->
    <FilterTable
      v-if="this.type === 'show'"
      ref="table3"
      :columns="columns3"
      :height="'200px'"
      :datakey="'rows'"
      :dataSource="datasourceTablethird"
      :params="fetchParams3"
      :onColumnsChange="columns => (this.columns3 = columns)"
      :isSelectColumn="false"
      :isPagination="false"
    >
      <template slot="controls"> </template>
    </FilterTable>

    <BaseDialog :visible.sync="showAddWxxm" title="维修项目选择" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addRepairItem :series="series" :seriesName="this.seriesName" @close="close" @change="addProjectInfo" />
    </BaseDialog>
    <BaseDialog :visible.sync="showaddPartSelection" title="配件选择" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <AddPartSelection ref="addPartSelection" :selectData="selectData" :AddProject="this.AddProject" @change1="addPartInfo" @close="close" />
    </BaseDialog>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">取 消</el-button>
      <AjaxButton v-if="this.type != 'show'" :click="saveAddform" type="primary" size="small">{{ btnText }}</AjaxButton>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import dictCode from '@/utils/dictCode';
import { getRepairTypes, findRepairProject, findRepairPart, btnSave, getAllAssembleHis, getAllSeries, getAllUser } from '@/api/repair/repairBusiness/repairPackage';
import addRepairItem from '@/pages/repair/repairBusiness/repairPackage_oem/addRepairItem';
import AddPartSelection from '@/pages/repair/repairBusiness/repairPackage_oem/addPartSelection';
import { getAppId } from '@/assets/js/auth';

// 延保订单查询
export default {
  name: 'repair-labourHour-info',
  props: {
    type: {
      // edit show add三种状态
      type: String,
      default: ''
    },
    info: {
      type: Object
    },
    seriesId: {
      type: String,
      default: ''
    }
  },
  components: { addRepairItem, AddPartSelection },
  mixins: [dictionary],
  data() {
    this.saveData = null;
    this.saveTabData = null;
    this.baseTable = null; // table1
    this.baseTable2 = null; // table2
    this.conf = { add: '保 存', edit: '保 存', show: '显  示' };
    return {
      formList: this.createFormList(),
      columns1: this.createTableColumns1(),
      columns2: this.createTableColumns2(),
      columns3: this.createTableColumns3(),
      showAddWxxm: false,
      showaddPartSelection: false,
      datasourceTablefirst: [],
      datasourceTablesecond: [],
      datasourceTablethird: [],
      fetchParams: { xhrAbort: true },
      fetchParams1: { xhrAbort: true },
      fetchParams3: { xhrAbort: true },
      display: false,
      labourcode: '',
      LABOUR_CODE: null,
      PACKAGE_CODE: null,
      labourIds: [], // 删除的维修项目
      partIds: [], // 删除的维修配件
      selectData: {},
      series: '', // 车系
      AddProject: false,
      AddProject1: false,
      AddRO: false,
      rowKey: 'A',
      seriesName: '', // 用于接收车系名称
      listSeries: [] // 定义车系的结果集
    };
  },

  computed: {
    btnText() {
      return this.conf[this.type];
    }
  },
  created() {
    this.getRepairTypesFun();
  },
  mounted() {
    this.baseTable = this.$refs.table1gjp.$refs.pageTable;
    this.baseTable2 = this.$refs.table2.$refs.pageTable;

    let APPID = getAppId();
    if (APPID == 'arcfox') {
      // beijing的不需要这2个字段
      this.formList.find(x => x.fieldName === 'CHARGE_PARTITION_CODE').hidden = false;
      this.formList.find(x => x.fieldName === 'IS_ISSUE_PACKAGE').hidden = false;
    }

    if (this.type != 'add') {
      this.findRepairProject(this.info.PACKAGE_CODE, this.info.PACKAGE_TYPE_NAME);
      // 传入的数据赋值
      this.formList.forEach(x => {
        x.initialValue = this.info[x.fieldName];
      });
    }
    if (this.type == 'show') {
      this.AddProject1 = true;
      this.AddProject = true;
      // this.formList.find(x => x.fieldName === 'PACKAGE_CODE').rules = [];
      this.formList.forEach(x => {
        x.rules = [];
        x.placeholder = '';
      });
      this.columns1.forEach(x => {
        x.defaultEditable = false;
        x.editable = false;
      });
      this.columns2.forEach(x => {
        x.defaultEditable = false;
        x.editable = false;
      });
      this.getAllAssembleHis();
    }
    this.getAllSeries();
    this.getAllUser();
  },
  methods: {
    async getAllUser() {
      let res = await getAllUser();
      if (res.resultCode == 200) {
        let allUser = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
        this.columns3.find(x => x.dataIndex === 'updateBy').dictItems = allUser;
      }
    },
    async getAllSeries() {
      let res = await getAllSeries();
      if (res.resultCode === 200) {
        let series = res.data.map(x => {
          return { value: x.seriesCode, text: x.seriesName };
        });
        this.formList.find(x => x.fieldName === 'SERIES_CODE').itemList = series;
        // this.columns1.find(x => x.dataIndex === 'SERIES_CODE').dictItems = series;
        // this.allSeries = res.data;
      }
    },
    // 获取变更履历
    async getAllAssembleHis() {
      let res = await getAllAssembleHis({ packageCode: this.info.PACKAGE_CODE });
      if (res.resultCode === 200) {
        if (res.data.length) {
          this.datasourceTablethird = res.data;
        }
      }
    },
    // 获取维修类型
    async getRepairTypesFun() {
      const res = await getRepairTypes();
      this.repairList = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
      this.formList.find(x => x.fieldName === 'REPAIR_TYPE_CODE').itemList = this.repairList;
    },
    createFormList() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '基本信息',
          style: {}
        },
        {
          type: 'INPUT',
          label: '套餐代码',
          fieldName: 'PACKAGE_CODE',
          placeholder: '请输入...',
          disabled: true,
          maxlength: 10
        },
        {
          type: 'INPUT',
          label: '套餐名称',
          fieldName: 'PACKAGE_TYPE_NAME',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          maxlength: 100
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'SERIES_CODE',
          placeholder: '请输入...',
          itemList: [],
          rules: [{ required: true, message: '请选择...', trigger: 'change' }],
          change: val => {
            // 把原先的数据放入待删除数组
            this.datasourceTablefirst.forEach(x => {
              this.labourIds.push(x.PACKAGE_LABOUR_ID);
            });
            this.datasourceTablesecond.forEach(x => {
              this.partIds.push(x.PACKAGE_PART_ID);
            });

            // 切换车系，清空原来选择的车
            this.series = val;
            this.datasourceTablefirst = [];
            this.datasourceTablesecond = [];
          }
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'REPAIR_TYPE_CODE',
          placeholder: '请选择...',
          rules: [{ required: true, message: '请选择...', trigger: 'change' }],
          itemList: []
        },

        {
          type: 'SELECT',
          label: '数据来源',
          fieldName: 'DATA_SOURCES',
          disabled: true,
          hidden: true,
          initialValue: 10451002,
          placeholder: '请选择...',
          itemList: this.createDictList('1045')
        },

        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'ASSEMBLE_STATUS',
          itemList: this.createDictList('1003'),
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '收费区分',
          fieldName: 'CHARGE_PARTITION_CODE',
          hidden: true,
          itemList: [
            { text: '免费', value: 'M' },
            { text: '索赔', value: 'S' },
            { text: '自费', value: 'Z' }
          ],
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '是否套餐包',
          fieldName: 'IS_ISSUE_PACKAGE',
          hidden: true,
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'TEXT_AREA',
          label: '套餐描述',
          fieldName: 'REMARK',
          selfCols: 4,
          maxlength: 300
        }
      ];
    },
    createTableColumns1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 110,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.DeleteProject(props.row)} disabled={this.type === 'show'}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '工时代码',
          dataIndex: 'LABOUR_CODE',
          sorter: true
        },
        {
          title: '工时名称',
          dataIndex: 'LABOUR_NAME',
          sorter: true
        },
        {
          title: '车系',
          dataIndex: 'SERIES_NAME',
          sorter: true
        },
        {
          title: '车型',
          dataIndex: 'MODEL_NAME',
          sorter: true
        },
        {
          title: '标准工时',
          dataIndex: 'STD_LABOUR_HOUR',
          sorter: true,
          render: props => {
            return <span>{props.row.STD_LABOUR_HOUR ? props.row.STD_LABOUR_HOUR : 0.0}</span>;
          }
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          hidden: true,
          sorter: true
        }
      ];
    },
    createTableColumns2() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 110,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.DeletePart(props.row)} disabled={this.type === 'show'}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true
        },
        {
          title: '配件单位',
          dataIndex: 'UNIT_CODE',
          hidden: true,
          sorter: true
        },
        {
          title: '配件单位',
          dataIndex: 'UNIT_NAME',
          sorter: true
        },
        {
          title: '配件数量',
          dataIndex: 'PART_QUANTITY',
          editable: true,
          defaultEditable: true,
          editType: 'number',
          precision: 2,
          min: 0,
          sorter: true
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          editable: true,
          defaultEditable: true,
          hidden: true,
          sorter: true
        }
      ];
    },
    createTableColumns3() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },

        {
          title: '变更前记录',
          dataIndex: 'beforeChange',
          sorter: true
        },
        {
          title: '变更后记录',
          dataIndex: 'afterChange',
          sorter: true
        },
        {
          title: '变更人',
          dataIndex: 'updateBy',
          sorter: true,
          dictItems: []
        },
        {
          title: '变更时间',
          dataIndex: 'updateAt',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true
        }
      ];
    },
    // 选完维修项目的回调
    addProjectInfo(val) {
      let addArr = [];
      val.forEach(x => {
        let result = this.datasourceTablefirst.find(item => item.ITEM_ID === x.ITEM_ID);
        if (!result) {
          addArr.push(x);
        }
      });

      this.baseTable.EXECUTE_INSERT(addArr);
      this.close();
      if (val.length !== addArr.length) {
        this.$notify.error({ title: '提示信息', message: '添加的数据存在重复' });
        return;
      }
    },
    // 选完配件的回调
    addPartInfo(val) {
      console.log('维修的配节', val);
      // 判断是否重复
      const element = val;
      let result = this.datasourceTablesecond.find(item => element.PART_NO === item.PART_NO);
      if (result) {
        this.$notify.error({ title: '提示信息', message: '添加的数据存在重复' });
        return;
      }

      this.baseTable2.EXECUTE_INSERT(val);
      this.close();
    },
    // 获取当前维修项目的数据
    addWXXM(val) {
      this.datasourceTablefirst = val;
    },
    // 点击删除，删除指定的维修项目
    DeleteProject(rows) {
      console.log(rows);
      this.labourIds.push(rows.PACKAGE_LABOUR_ID);
      // this.baseTable.EXECUTE_DELETE([rows]);
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(this.datasourceTablefirst);
          this.datasourceTablefirst.splice(rows.index, 1);
          this.datasourceTablefirst = [...this.datasourceTablefirst];
        })
        .catch(() => {});
    },
    // 点击删除，删除指定的维修配件
    DeletePart(rows) {
      this.partIds.push(rows.PACKAGE_PART_ID);
      // this.baseTable2.EXECUTE_DELETE([rows]);
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(this.datasourceTablesecond);
          this.datasourceTablesecond.splice(rows.index, 1);
          this.datasourceTablesecond = [...this.datasourceTablesecond];
        })
        .catch(() => {});
    },
    // 明细或编辑时进行编译
    async findRepairProject(code, name) {
      this.rowKey = 'U';
      this.formList.find(item => item.fieldName === 'PACKAGE_CODE').disabled = true;
      const res = await findRepairProject(code, name);

      if (res.data) {
        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].MODEL_LABOUR_CODE != null) {
            res.data[i].MODEL_LABOUR_CODE = res.data[i].MODEL_LABOUR_CODE + '';
          }
        }
        // 存在才插入
        this.baseTable.EXECUTE_INSERT(res.data);
      }
      const resss = await findRepairPart({ packageCode: code, powerType: '', dataSources: this.info.DATA_SOURCES });
      if (resss.data) {
        // 存在才插入
        this.baseTable2.EXECUTE_INSERT(resss.data);
      }
      console.log('明细：', res.data, resss.data);
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    // 保存所有数据
    async saveAddform() {
      let result = this.$refs.formPanel.SUBMIT_FORM(); // 会去校验，并提示。不需要自己再单独判断
      if (!result) return;

      if (!this.datasourceTablefirst.length) {
        return this.$notify.warning({ title: '提示信息', message: '维修项目不能为空' });
      }
      // 配件不存在可以，存在必须校验数量
      console.log(this.$refs.table2.$refs.pageTable.dataSource);
      let array = this.$refs.table2.$refs.pageTable.dataSource;
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (element.PART_QUANTITY <= 0) {
          return this.$notify.warning({ title: '提示信息', message: '配件数量不能为空' });
        }
      }
      let Json = {};
      Json['dmsLabour'] = this.datasourceTablefirst;
      Json['dmsPart'] = this.$refs.table2.$refs.pageTable.dataSource;
      Json['dmsCompose'] = this.$refs.formPanel.SUBMIT_FORM();
      Json['labourIds'] = this.labourIds.join();
      Json['partIds'] = this.partIds.join();
      Json['rowKey'] = this.rowKey;
      let res = await btnSave(Json);
      if (res.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '保存成功' });
        // this.$emit('close');
        this.$emit('close', false, 'refresh');
      }
    },
    // 新增维修项目按钮
    async openAddWxxm() {
      let seriesCode = this.formList.find(x => x.fieldName === 'SERIES_CODE').initialValue;
      if (seriesCode) {
        this.series = seriesCode;
        this.showAddWxxm = true;
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请先选择车系' });
      }
    },
    // 新增配件按钮
    openReCom() {
      this.selectData = this.datasourceTablefirst;
      this.showaddPartSelection = true;
    },

    close() {
      this.showAddWxxm = false;
      this.showaddPartSelection = false;
    },
    closeDialog() {
      this.$emit('close');
    }
  }
};
</script>
